<template>
	<view >
		<!-- <view class="title">请在下面输入签名：</view> -->
		<image :style="`width: ${canvasWidth}px; height: ${canvasHeight}px; `" :src=image_url > </image>
		<canvas id="myCanvas" class="myCanvas"  :style="`width: ${canvasWidth}px; height: ${canvasHeight}px; `" canvas-id="myCanvas"  @mousedown="touchstart" @mousemove="touchmove" @mouseup="touchend"></canvas>
		<!-- <canvas id="myCanvas" class="myCanvas" canvas-id="myCanvas"  @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"></canvas> -->
		
		<view class="footer">
			
			<view style="position: relative;">
				<!-- <text style="color: azure;">设置画笔粗细：</text> -->
				<slider style="width: 300px;" min=5 max=80 step="5" v-model="line_width" value="line_width" @change="sliderChange" activeColor="#1EFFE7" backgroundColor="#FFFFFF" block-color="#1EFFE7" block-size="15" />
			</view>
			<view class="left" @click="finish">编辑完成</view>
			<view class="right" @click="clear">清除</view>
			<!-- <view class="right" @click="backStep">撤销</view> -->
			<!-- <view class="right" @click="canvasRedo">反撤销</view> -->
		</view>
	</view>
</template>

<script>
	var x = 20;
	var y =20;
	export default{
		name: 'mengban',
		props: {
			// 开启动画
			canvasWidth: {
				type: Number,
				default: 820
			},
			// 弹出层类型，可选值，top: 顶部弹出层；bottom：底部弹出层；center：全屏弹出层
			canvasHeight: {
				type: Number,
				default: 800
			},
			// maskClick
			image_url: {
				type: String,
				default: "./a.jpg"
			}
		},
		
		data(){
			return {
				ctx:'',         //绘图图像
				canDraw: false,
				points:[],       //路径点集合 
				canvasHistory : [],
				step : 0,
				
				line_width : 20,
				
			}
		},
		created() {
			this.ctx = uni.createCanvasContext("myCanvas",this);   //创建绘图对象
			
			//设置画笔样式
			this.ctx.lineWidth = this.line_width;
			this.ctx.strokeStyle= '#fff'
			this.ctx.lineCap = "round"
			this.ctx.lineJoin = "round"
			
			console.log(this.ctx)
			
		},
		
		methods:{
			sliderChange(e){
				this.line_width = e.detail.value
				this.ctx.lineWidth = this.line_width
			},
			//触摸开始，获取到起点
			touchstart:function(e){
				
				var canvas_pos = document.getElementById("myCanvas").getBoundingClientRect();
				this.canvas_x = canvas_pos.x
				this.canvas_y = canvas_pos.y
				this.canDraw = true;
				let startX = e.clientX - this.canvas_x;
				let startY = e.clientY - this.canvas_y;
				let startPoint = {X:startX,Y:startY};
				this.points.push(startPoint);
				//每次触摸开始，开启新的路径
				this.ctx.beginPath();
			},
			
			//触摸移动，获取到路径点
			touchmove:function(e){
				if(this.canDraw){
					var canvas_pos = document.getElementById("myCanvas").getBoundingClientRect();
					
					this.canvas_x = canvas_pos.x
					this.canvas_y = canvas_pos.y
					let moveX = e.clientX - this.canvas_x;
					let moveY = e.clientY - this.canvas_y;
					let movePoint = {X:moveX,Y:moveY};
					this.points.push(movePoint);       //存点
					let len = this.points.length;
					if(len>=2 && this.canDraw){
						this.draw();                   //绘制路径
					}
				}
				
				
			},
			
			// 触摸结束，将未绘制的点清空防止对后续路径产生干扰
			touchend:function(){   
				console.log('end')     
				this.canDraw = false;
				this.points=[];
				this.saveCurrentDrawWorks() // 添加新的绘制到历史记录
			},
			
			/* ***********************************************
			#   绘制笔迹
			#	1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
			#	2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
			#	3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
			************************************************ */
			draw: function() {
				this.step++;
				if (this.step < this.canvasHistory.length) {
					this.canvasHistory.length = this.step; // 截断数组
				}
				// 执行绘制的相关操作（如绘制图片、线条等）
				let point1 = this.points[0]
				let point2 = this.points[1]
				this.points.shift()
				this.ctx.moveTo(point1.X, point1.Y)
				this.ctx.lineTo(point2.X, point2.Y)
				this.ctx.stroke()
				this.ctx.draw(true)
				

			},
			
			//清空画布
			clear:function(){
				let that = this;
				uni.getSystemInfo({
					success: function(res) {
						let canvasw = res.windowWidth;
						let canvash = res.windowHeight;
						that.ctx.clearRect(0, 0, canvasw, canvash);
						that.ctx.draw(true);
					},
				})
			},
			saveImg(url) {
					var oA = document.createElement("a");
					oA.download = ''; // 设置下载的文件名，默认是'下载'
					oA.href = url;
					document.body.appendChild(oA);
					oA.click();
					oA.remove(); // 下载之后把创建的元素删除
			},
			saveCurrentDrawWorks(){
				let that = this;
				var canvas_pos = document.getElementById("myCanvas").getBoundingClientRect();
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: that.canvasWidth,
					height: that.canvasHeight,
					canvasId: 'myCanvas',
					success: function(res) {
						var imgPath = res.tempFilePath;
						that.canvasHistory = [...that.canvasHistory, imgPath];
						console.log(that.canvasHistory.length)
					} 
				});
			},
			//完成绘画并保存到本地
			finish:function(){
				var that = this
				uni.canvasToTempFilePath({
				  canvasId: 'myCanvas',
				  success: function(res) {
					  console.log(res)
				    let path = res.tempFilePath;
					// that.saveImg(path);
					that.$emit('finish', [path,that.canvasHistory[that.canvasHistory.length-1]]);
				  } 
				})
			},
			
			 backStep() {
				 
				var allDrawWorksPath = this.canvasHistory;
				if (allDrawWorksPath == null || allDrawWorksPath.length == 0 || allDrawWorksPath == undefined) {
					this.clear()
					// uni.showToast({
					// 	icon: 'none',
					// 	title: '已经撤销到起始位置'
					// });
					this.canvasHistory = [];
					return;
				}
				var privWorksPath = allDrawWorksPath.pop();
				// this.canvasHistory = allDrawWorksPath;
				// let canvasPic = new Image();
				// canvasPic.src = privWorksPath;
				// canvasPic.addEventListener('load', () => {
				//   this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
				//   console.log(11111111)
				//   this.ctx.drawImage(canvasPic, 0, 0, this.canvasWidth, this.canvasHeight);
				//   console.log(22222222)
				//   // this.ctx.draw()
				//   console.log(3333333)
				// });
				this.ctx.draw()
				this.ctx.lineWidth = this.line_width;
				this.ctx.strokeStyle= '#fff'
				this.ctx.lineCap = "round"
				this.ctx.lineJoin = "round"
			},
			// 撤销方法
			canvasUndo() {
			  if (this.step >= 0) {
			    this.step--;
			    this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
			    let canvasPic = new Image();
			    canvasPic.src = this.canvasHistory[this.step];
			    canvasPic.addEventListener('load', () => {
					this.ctx.drawImage(canvasPic, 0, 0, this.canvasWidth, this.canvasHeight);
					this.ctx.stroke();
					let that = this;
					uni.drawCanvas({
						canvasId: 'myCanvas',
						reserve: true,
						actions: that.ctx.getActions() // 获取绘图动作数组
					});
			    });
			  } else {
			    console.log('不能再继续撤销了');
			  }
			},
			// 反撤销方法
			canvasRedo() {
			  if (this.step < this.canvasHistory.length - 1) {
			    this.step++;
			    let canvasPic = new Image();
			    canvasPic.src = this.canvasHistory[step];
			    canvasPic.addEventListener('load', () => {
			      this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
			      this.ctx.drawImage(canvasPic, 0, 0);
			    });
			  } else {
			    console.log('已经是最新的记录了');
			  }
			}
		},
	}
</script>

<style>
	.title{
		height:50upx;
		line-height: 50upx;
		font-size: 16px;
	}
	.myCanvas{
		position: absolute;
		top: 0;
		/* width: 100%;
		height: calc(100vh - 200upx); */
		width: 800px;
		height: 800px;
		/* background-color: #ECECEC; */
		
	}
	.footer{
		font-size: 16px;
		height: 150upx;
		display: flex;
		justify-content: space-around;
		align-items: center;
	}
	.left,.right{
		line-height: 100upx;
		height: 100upx;
		width: 250upx;
		text-align: center;
		font-weight: bold;
		color: white;
		border-radius: 5upx;
	}
	.left{
		background: #007AFF;
	}
	.right{
		background:orange;
	}
</style>

